"""
演示将数据库中的数据读出
"""
import pymysql
from pymysql import Connection
import json

# 链接数据库
conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="hzh3589153651",
    autocommit=True
)
# 读取数据库中的数据
# 选择数据库
conn.select_db('py_sql')
# 获取游标对象
cursor = conn.cursor()
# 执行sql语句
cursor.execute("select * from orders")
result = cursor.fetchall()
# 关闭游标和连接
cursor.close()
# 将结果转换为JSON格式并保存到文件中
with open('orders_data.txt', 'w', encoding='utf-8') as file:
    for row in result:
        json_data = json.dumps({"data":str(row[0]),
                                "order_id":str(row[1]),
                                "money":row[2],
                                "province":str(row[3])},
                               ensure_ascii=False)
        file.write(json_data + '\n')
print("数据已保存到orders_data.json文件中")
